package traverser;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Scanner;

public class ConcurrencyTest extends Thread {
	
	private static String [] pages;
	private static final int MAX_PAGES = 30;
	private static final int MAX_THREADS = 30;
	
	private int start;
	private int stop;
	
	public ConcurrencyTest (int start, int stop) {
		this.start = start;
		this.stop = stop;
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
		pages = new String[MAX_PAGES];
		for (int i = 0; i < pages.length; i++) {
			pages[i] = FrequencyCollector.getRandomPage();
			System.out.println(pages[i]);
		}
		
		for (int threads = 1; threads < MAX_THREADS; threads++) {
			System.out.println("Running with " + threads + " threads");
			
			ConcurrencyTest [] pool = new ConcurrencyTest[threads];
			for (int t = 0; t < threads; t++) {
				int ppt = MAX_PAGES / threads;
				int start = ppt * t;
				int stop = ppt * (t+1);
				pool[t] = new ConcurrencyTest(start, stop);
			}
			
			long startTime = System.currentTimeMillis();
			
			for (int t = 0; t < threads; t++) {
				pool[t].start();
			}
			
			for (int t = 0; t < threads; t++) {
				try {
					pool[t].join();
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					System.exit(1);
				}
			}
			
			long endTime = System.currentTimeMillis();
			long runTime = endTime - startTime;
			System.out.println("Time with " + threads + " threads: " + runTime);
			
		}
		

	}
	
	public void run () {
		for (int i = start; i < stop; i++) {
			getHTML(pages[i]);
		}
	}

	// gets HTML code from website and puts it in htmlCode
	public void getHTML(String website) {
		URL site = null;
		InputStream contentStream = null;

		// Attempt to connect to the page MAX_ATTEMPTS times
		try {
			site = new URL(website);
			contentStream = site.openStream();
		} catch (IOException e) {
			System.err.println("Error connecting to " + website + ".  Message:");
			System.err.println(e.getMessage());
			return;
		}

		Scanner sc = new Scanner(contentStream);
		String htmlCode = "";
		while (sc.hasNext()) {
			htmlCode += sc.nextLine();
		}
		return;
	}

}
